package com.kotiln.lgc.sunnyweather.activity

import android.content.Context
import android.graphics.Color
import android.icu.text.SimpleDateFormat
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.kotiln.lgc.sunnyweather.R
import com.kotiln.lgc.sunnyweather.databinding.ActivityWeatherBinding
import com.kotiln.lgc.sunnyweather.logic.model.Weather
import com.kotiln.lgc.sunnyweather.logic.model.WeatherViewModel
import com.kotiln.lgc.sunnyweather.logic.model.getSky

import java.util.*

/**
 *@fileName WeatherActivity
 *@date2020/12/1  18:07
 *@author WeatherActivity$
 *@describe TODO
 *@desc
 */
class WeatherActivity : AppCompatActivity() {
    private lateinit var binding: ActivityWeatherBinding
    public lateinit var drawerLayout: DrawerLayout
     val viewModel by lazy {
        ViewModelProviders.of(this).get(WeatherViewModel::class.java)
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //将状态栏和背景图融为一体
        val decorView = window.decorView
        decorView.systemUiVisibility =View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        window.statusBarColor = Color.TRANSPARENT
        binding=ActivityWeatherBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //打开滑动菜单
        val navBtn=findViewById<TextView>(R.id.navBtn)
         drawerLayout=findViewById<DrawerLayout>(R.id.drawerLayout)

        navBtn.setOnClickListener{
            drawerLayout.openDrawer(GravityCompat.START)
            showBottomSheetDialog()
        }
        //监听DrawerLayout状态
        binding.drawerLayout.addDrawerListener(object: DrawerLayout.DrawerListener{
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
            }

            override fun onDrawerOpened(drawerView: View) {
            }

            override fun onDrawerClosed(drawerView: View) {
                //关闭时调用
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(drawerView.windowToken,InputMethodManager.HIDE_NOT_ALWAYS)
            }

            override fun onDrawerStateChanged(newState: Int) {


            }

        })

        //获取经纬度数据
        if (viewModel.locationLng.isEmpty()) {
            viewModel.locationLng = intent.getStringExtra("location_lng") ?: ""
        }
        if (viewModel.locationLat.isEmpty()) {
            viewModel.locationLat = intent.getStringExtra("location_lat") ?: ""
        }
        if (viewModel.placeName.isEmpty()) {
            viewModel.placeName = intent.getStringExtra("place_name") ?: ""
        }

         viewModel.weatherLiveData.observe(this, Observer { result ->
            val weather = result.getOrNull()
            if (weather != null) {
                showWeatherInfo(weather)
            } else {
                Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }
            binding.swipeRefresh.isRefreshing = false
        })


        //下拉刷新数据
        binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
        refreshWeather()
        binding.swipeRefresh.setOnRefreshListener {
            refreshWeather()
        }

    }

     fun refreshWeather() {

        viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat)
         binding.swipeRefresh.isRefreshing = true
    }

    @RequiresApi(Build.VERSION_CODES.N)
    private fun showWeatherInfo(weather: Weather) {
        val placeName=findViewById<TextView>(R.id.placeName)
        placeName.text = viewModel.placeName
        val realtime = weather.realtime
        val daily = weather.daily
        //填充now.xml布局中的数据
        val currentTempText = "${realtime.temperature.toInt()} C"
        val currentTemp=findViewById<TextView>(R.id.currentTemp)
        currentTemp.text = currentTempText
        val currentSky=findViewById<TextView>(R.id.currentSky)
        currentSky.text = getSky(realtime.skycon).info
        val currentPM25Text = "空气指数${realtime.airQuality.aqi.chn.toInt()}"
        val currentAQI=findViewById<TextView>(R.id.currentAQI)
        currentAQI.text = currentPM25Text
        val nowLayout=findViewById<RelativeLayout>(R.id.nowLayout)
        nowLayout.setBackgroundResource(getSky(realtime.skycon).bg)
        //填充forecast.xml布局中的数据
        val forecastLayout=findViewById<LinearLayout>(R.id.forecastLayout)
        forecastLayout.removeAllViews()
        val days = daily.skycon.size
        for (i in 0 until days) {
            val skycon = daily.skycon[i]
            val temperature = daily.temperature[i]
            val view =
                LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false)
            val dateInfo = view.findViewById(R.id.dateInfo) as TextView
            val skyIcon = view.findViewById(R.id.skyIcon) as ImageView
            val skyInfo = view.findViewById(R.id.skyInfo) as TextView
            val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView
            val simpleDateFormat = SimpleDateFormat("yyyy-mm-dd", Locale.getDefault())
            dateInfo.text = simpleDateFormat.format(skycon.date)
            val sky = getSky(skycon.value)
            skyIcon.setImageResource(sky.icon)
            skyInfo.text = sky.info
            val tempText = "${temperature.min.toInt()} ~${temperature.max.toInt()} C"
            temperatureInfo.text = tempText
            forecastLayout.addView(view)
        }
        //填充life_index.xml布局中的数据
        val lifeIndex = daily.lifeIndex
        val coldRiskText=findViewById<TextView>(R.id.coldRiskText)
        coldRiskText.text = lifeIndex.coldRisk[0].desc
        val dressingText=findViewById<TextView>(R.id.dressingText)
        dressingText.text = lifeIndex.dressing[0].desc
        val ultravioletText=findViewById<TextView>(R.id.ultravioletText)
        ultravioletText.text = lifeIndex.ultraviolet[0].desc
        val carWashingText=findViewById<TextView>(R.id.carWashingText)
        carWashingText.text = lifeIndex.carWashing[0].desc
        val weatherLayout=findViewById<ScrollView>(R.id.weatherLayout)
        weatherLayout.visibility = View.VISIBLE
    }

    /**
     * 从下而上的弹框
     */
    fun showBottomSheetDialog(){
        val bottomSheetDialog= BottomSheetDialog(this)
        bottomSheetDialog.window?.setWindowAnimations(R.style.MyBottomSheetDialogAnimation)
        val view=layoutInflater.inflate(R.layout.bottom_sheet_dialog,null)
//        bottomSheetDialog.setDuration(1000) //需要使用动画的setDuration，BottomSheetDialog本身没有这个方法
        bottomSheetDialog.setContentView(view)
        bottomSheetDialog.show()

    }

}